/*
 * mhtxtmedia.cpp
 *
 *  Created on: 2010-8-26
 *      Author: angelstone
 */
#include <wx/wx.h>
#include <wx/filename.h>

#include "mhcontext.h"
#include "mhmedia.h"
#include "mhtxtmedia.h"

using namespace mediahouse;

int CMHTxtMediaAddon::CanHandleMedia(CMHContext * pContext,
		hiberlite::bean_ptr<mediahouse::CMHMedia> & media, void * cookies) {
	wxString loc = media->GetLocation();

	if (wxDirExists(loc))
		return 0;

	if (!wxFileExists(loc))
		return 0;

	wxFileName fname;
	fname.Assign(loc);

	wxString ext = fname.GetExt().Lower();

	return ext == wxT("txt") || ext == wxT("html") || ext == wxT("htm") ? 1 : 0;
}

int CMHTxtMediaAddon::HandleMedia(CMHContext * pContext, hiberlite::bean_ptr<
		mediahouse::CMHMedia> & media, void * cookies) {

	if (!CanHandleMedia(pContext, media, cookies))
		return 0;

	wxString base_loc = wxEmptyString;

	if (media->HasProperty(wxT("base_location"))) {
		media->GetProperty(wxT("base_location"), base_loc);
	}

	wxString category = PrepareCategory(pContext, wxT("/eBooks"), base_loc,
			media->GetLocation());

	media->SetProperty(wxT("category"), category);
	media->SetModified(wxFileModificationTime(media->GetLocation()));

	return 1;
}

wxString CMHTxtMediaAddon::PrepareCategory(CMHContext * pContext,
		const wxString & base_category, const wxString & base_loc,
		const wxString & loc) {
	wxFileName fname;
	fname.Assign(loc);

	wxString category = base_category;

	if (!base_loc.IsEmpty()) {
		fname.MakeRelativeTo(base_loc, wxPATH_UNIX);

		category += wxT("/") + wxPathOnly(fname.GetFullPath(wxPATH_UNIX));
	}

	wxString fullId;

	pContext->FindCategoryFullId(category, fullId, true);

	return fullId;
}
